<%@ page pageEncoding="UTF-8"%>
<%@ page import="java.util.Map.Entry,java.util.*,java.util.regex.*,java.net.*,java.io.*,java.text.*"%>
<%@ page import="com.tianxiabuyi.*,com.tianxiabuyi.db.*,com.tianxiabuyi.model.*,com.tianxiabuyi.util.*"%>
<%@ page import="org.jsoup.Jsoup,org.jsoup.nodes.Element,org.jsoup.select.Elements"%>
<%@ page import="com.google.gson.reflect.TypeToken"%>
<%@ page import="org.dom4j.*"%>
<%@ include file = "operatehistory.jsp"%>
<%@ include file = "user.jsp"%>
<%!
	// 新闻列表
	String list(Input input) {
		Integer page = 1; // 页码
		Integer itemCount = 20; // 每一页条目
		String category = input.getDesc("category", "1"); // 新闻类别
		Integer hospital = input.getInt("hospital", -1); // 医院id
		String sinceID = input.getDesc("since_id","0"); // 下拉刷新
		String maxID = input.getDesc("max_id","0"); // 上拉加载
		hospital = input.getInt("branch", hospital);
		Integer uuid = input.getInt("uid", -1);
		String order = "desc"; // 排序
		String newsId = "";
		String selectContent = selectContent = "distinct new map(n.id as id , n.newsId as news_id, n.url as url, n.title as title, n.summary as summary, n.time as time, n.img as img, n.jsonString as json, n.category as category, n.author as author)" ;
		if (!sinceID.equals("0")) {
			newsId = "n.newsId > " + sinceID;
			order = "asc";
		} else if (!maxID.equals("0")) {
			newsId = "n.newsId < " + maxID;
		}
		List newsList = QBuilder.db("basedb").select(selectContent).from("News as n").where(new Where("n.hospital=", hospital).and("n.category=", category).and("n.status = ", STATUS_ENABLE).and(newsId)).order("n.newsId", order).page(itemCount, page).query().getResultObj();
		String label = input.getDesc("label", "");
		// 根据标签查询，数据示例(1,2,3)
		if (!"".equals(label)) {
			newsList = QBuilder.db("basedb").select(selectContent).from("News as n, LabelRelation as l").where(new Where("n.hospital=", hospital).and("n.category=", category).and("n.status = ", STATUS_ENABLE).and("n.id=l.targetId").and("l.labelId in " + label).and("l.status=", STATUS_ENABLE).and(newsId)).order("n.newsId", order).page(itemCount, page).query().getResultObj();
		}
		if (order.equals("asc")) { // 上拉加载时倒序
			Collections.reverse(newsList);
		}
		Message msg = new Message(0);
		OperateHistory oh = new OperateHistory();
		oh.setHospital(hospital);
		oh.setCategory(NEWS_CATEGORY);
		oh.setOperate(LOVE);
		msg.put("news", love(query(newsList, oh), uuid, oh));
		return msg.toJson();
	}

	// 新闻详情
	String article(Input input) {
		Integer hospital = input.getInt("hospital", -1); // 医院id
		Integer newsId = input.getInt("news_id", -1); // 新闻id
		hospital = input.getInt("branch", hospital);
		Integer uuid = input.getInt("uid", -1);
		List article = QBuilder.db("basedb").select("new map(id as id, title as title, time as time, summary as summary, author as author, content as content, img as img, jsonString as json)").from("News").where(new Where("hospital=", hospital).and("newsId =", newsId).and("status = ", STATUS_ENABLE)).query().getResultObj();
		Message msg = new Message(0);
		if (article.size() == 0) {
			setErrcode(msg, NEWS_NOT_FOUND);
			return msg.toJson();
		}





		Map<String, Object> news = (Map<String, Object>)article.get(0);
		String content = Tools.getDesc(news.get("content"));
		content = content.replaceAll( "\"", "&quot;");
		news.put("content", content);

		List<OperateHistory> ohList = QBuilder.db("basedb").queryHql("from OperateHistory where   oid="+ newsId+" and operate=3 and hospital = 1070 and status =1");



		news.put("count", ohList.size());
		int is_loved = 0 ;
		for(OperateHistory oh : ohList){
			if((uuid+"").equals(oh.getUid()+"")){
				is_loved=1;
				news.put("loved_id", oh.getId());
			}
		}
		news.put("is_loved", is_loved);

		msg.put("news", news);
		OperateHistory oh = new OperateHistory();
		oh.setHospital(hospital);
		oh.setCategory(NEWS_CATEGORY);
		oh.setUid(uuid+"");
		oh.setOid(news.get("id")+"");
		oh.setOperate(SEE);
		operate(oh, false);
		List<Map> commentList = QBuilder.db("basedb").select("new map(id as id,case when imgs is null then '[]' else imgs end as imgs, uid as uid, content as content, cTime as create_time)").from("Comment").where(new Where("srcId=", news.get("id")).and("hospital=", hospital).and("category=", 2)).order("id", "asc").query().getResultObj();
		List<Integer> uidList = new ArrayList<Integer>();
		for (int i = 0; i < commentList.size(); i++) {
			Map comment = commentList.get(i);
			Integer uid = Tools.getInt(comment.get("uid") + "", 0);
			Long createTime = Tools.getLong(comment.get("create_time") + "");
			String create_time = DateUtil.formatDateByFormat(new Date(createTime), DateUtil.DATETIME_FORMAT);
			comment.put("create_time", create_time);
			uidList.add(uid);
		}
		Map<Integer, User> userMap = usersByUids(uidList);
		for (int i = 0; i < commentList.size(); i++) {
			Map comment = (Map)commentList.get(i);
			Integer uid = Tools.getInt(comment.get("uid") + "", 0);
			comment.remove("uid");
			User user = userMap.get(uid);
			if (user != null) {
				String userName = user.getUserName();
				String avatar = user.getAvatar();
				String name = user.getName();
				comment.put("user_name", userName);
				comment.put("name", name);
				comment.put("avatar", avatar);
				comment.put("type", user.getType());  // 用于判断回答用户的角色
			}
		}
		msg.put("comment", commentList);
		return msg.toJson();
	}

	// 替换抓取新闻标题中可能出现的特殊字符
	public String replaceTitle(String title) {
		title = Tools.getDesc(title, "");
		title = title.replaceAll("\"", "&quot;").replaceAll(":", "&#58;");
		return title;
	}

	// 替换新闻内容中的html标签
	public String replaceContent(String html) {
		html = Tools.getDesc(html, "");
		html = html.toLowerCase();
		html = html.replaceAll("<p[^>]*?>", "<p>");
		html = html.replaceAll("<div[^>]*?>", "<p>");
		html = html.replaceAll("</div>", "</p>");
		html = html.replaceAll("<font[^>]*?>", "");
		html = html.replaceAll("<b(?!r)[^>]*?>", "");
		html = html.replaceAll("<span[^>]*?>","");
		html = html.replaceAll("</span>","");
		html = html.replaceAll("</font>","");
		html = html.replaceAll("<br[^>]*?>","<br/>");
		html = html.replaceAll("<style[^>]*?>[\\s\\S]*?<\\/style>","");
		html = html.replaceAll("<a[^>]*?>","");
		html = html.replaceAll("</a>", "");
		html = replaceTitle(html);
		int i = 0;
		while(html.indexOf("<img") > -1) {
			html = html.replaceFirst("<img[^>]*?>", "!--IMG#" + (i++)  + "--");
		}
		return html;
	}

	// 抓取远程图片到本地服务器，并返回本地服务器地址集合
	public String imgs(Element content, String domian) {
		Elements imgs = content.select("img");
		List<HashMap<String, String>> imgsJson = new ArrayList<HashMap<String, String>>();
		int size = imgs.size();
		for(int i = 0; i < size; i++) {
			String src = imgs.get(i).attr("src").toString();
			String domianIgnore = domian.replace("www.","");
			if((!src.startsWith(domian)) && (!src.startsWith(domianIgnore))) {
				src = domian + src;
			}

			String big = ImageUtil.big(src);
			String sizeJson = ImageUtil.size(big);
			String pixel  = "550 * 366";
			List<HashMap<String, String>> sizeList = GsonUtil.fromJson(sizeJson, new TypeToken<List<HashMap<String, String>>>(){});
			if(sizeList.size() > 0) {
				HashMap<String, String> sizeMap = sizeList.get(0);
				pixel = sizeMap.get("width") + " * " + sizeMap.get("height");
			}

			// 存入HashMap中
			HashMap<String, String> map = new HashMap<String, String>();
			map.put("ref","!--IMG#" + i + "--");
			map.put("pixel", pixel);
			map.put("src", big);
			// 循环添加某篇新闻
			imgsJson.add(map);
		}
		return GsonUtil.toJson(imgsJson);
	}

	// 如果医院新闻id不为数字，使用本地服务器流水号
	public void genNewsId(List<Integer> ids, int hospital) {
		StringBuffer buffer = new StringBuffer();
		for (int i = 0; i < ids.size(); i++) {
			buffer.append(ids.get(i)).append(",");
		}
		if (buffer.length() == 0) return;
		String allId = buffer.toString();
		allId = allId.substring(0, allId.length() -1);

		List<News> list = QBuilder.db("basedb").queryHql("from News where hospital='" + hospital + "' and id in(" + allId + ")");
		for (int i = 0; i < list.size(); i++) {
			News news = list.get(i);
			int id = news.getId();
			news.setNewsId(news.getId());
		}
		DBTools.db("basedb").modItem(list);
	}

	// 替换图片
	public Map replaceImage(String html, String domian) {
		if (html == null) return new HashMap();
		html = html.replaceAll("\"", "");
		org.jsoup.nodes.Document doc = Jsoup.parse(html);
		Elements imgs = doc.select("img");
		List<Map<String, String>> imgList = new ArrayList<Map<String, String>>();
		for (int i = 0; i < imgs.size(); i++) {
			Element img = imgs.get(i);
			String src = img.attr("src").toString();
			String domianIgnore = domian.replace("www.","");
			if((!src.startsWith(domian)) && (!src.startsWith(domianIgnore))) {
				src = domian + src;
			}
			String big = ImageUtil.big(src);
			Map<String, String> imgMap = new HashMap<String, String>();
			imgMap.put("src", big);
			imgList.add(imgMap);

			html = html.replace(img.attr("src").toString(), big);
		}

		Map returnMap = new HashMap();
		returnMap.put("html", html);
		returnMap.put("imgs", imgList);
		return returnMap;
	}


	public List<Map> cate(Input input) {
		Integer parent = input.getInt("parent", -1);	 // 父类id,传0表示既没有大类也没有小类
		Integer hospital = input.getInt("hospital", -1); // 医院id
		List<Map> list = QBuilder.db("basedb").select("new map(id as id, name as name, parent as parent, jsonString as json)").from("NewsGroup").where(new Where("hospital=", hospital).and("status=", STATUS_ENABLE).and("parent=", parent)).order("order", "asc").query().getResultObj();
		for (int i = 0; i < list.size(); i ++) {
			Map aMap = list.get(i);
			Integer parentId = Tools.getInt(aMap.get("id") + "", -1);
			input.setDesc("parent", parentId + "");
			aMap.put("sub", cate(input));
		}
		return list;
	}

	// 新闻分类
	public String category(Input input) {
		Message msg = new Message();
		List<Map> list = cate(input);
		for (Map map:list) {
			map.put("icon", GsonUtil.fromJson(Tools.getDesc(map.get("json")), new TypeToken<Map>(){}).get("icon"));
			map.remove("json");
		}
		msg.put("category", list);
		return msg.toJson();
	}


	// 评论
	String reply(Integer uid, Input input) {
		Message msg = new Message(0);
		Integer newsId = input.getInt("id", 0);
		String content = input.getDesc("content", "");
		Integer hospital = input.getInt("hospital", -1);
		if (content.length() < 3) {
			setErrcode(msg, LENGTH_ILLEGAL);
			return msg.toJson();
		}
		List<News> newsList = QBuilder.db("basedb").queryHql("from News where id = " + newsId);
		if (newsList.size() == 0) {
			setErrcode(msg, NO_RESULT);
			return msg.toJson();
		}
		com.tianxiabuyi.model.Comment comment = new com.tianxiabuyi.model.Comment();
		comment.setHospital(hospital);
		comment.setUid(uid);
		comment.setSrcId(newsId);
		comment.setContent(content);
		comment.setCategory(2);
		String imgs = input.getDesc("imgs", Tools.encryptStr("[]"));
		comment.setImgs(Tools.decryptStr(imgs));
		DBTools.db("basedb").addItem(comment);
		return msg.toJson();
	}
%>
